package com.xxx.ware.ware_manage_sys.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisClient {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成唯一id
     * @param key redis中的key
     * @return
     */
    public String genSoleId(String key){
        Long increment = redisTemplate.opsForValue().increment(key);
        String formattedNumber = String.format("%06d", increment);
        Long timeStamp = System.currentTimeMillis() / 1000;
        return timeStamp + "-" + formattedNumber;
    }

    /**
     * 删除key
     * @param key redis的key
     * @return
     */
    public Boolean delDataByKey(String key){
        Boolean delResult = redisTemplate.delete(key);
        return delResult;
    }

    /**
     * 设置缓存（有过期时间）
     * @param key
     * @param val
     * @param exprieTime
     * @return
     */
    public Boolean setData(String key, Object val, Long exprieTime){
        try {
            redisTemplate.opsForValue().set(key, val, exprieTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.warn("缓存数据异常，异常原因：" + e);
            return false;
        }
    }

    /**
     * 设置缓存
     * @param key
     * @param val
     * @return
     */
    public Boolean setData(String key, Object val){
        try {
            redisTemplate.opsForValue().set(key, val);
            return true;
        } catch (Exception e) {
            log.warn("缓存数据异常，异常原因：" + e);
            return false;
        }
    }

    /**
     * 获取缓存数据
     * @param key 缓存key
     * @return
     */
    public Object getData(String key){
        Object resData = redisTemplate.opsForValue().get(key);
        return resData;
    }
}
